<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入检测站名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="联系电话" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入联系电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="isEnable">
        <el-select v-model="queryParams.isEnable" placeholder="是否启用" clearable size="small">
          <el-option v-for=" dict in enableOptions"
                     :key="dict.dictValue"
                     :label="dict.dictLabel"
                     :value="dict.dictValue"/>
        </el-select>
      </el-form-item>
      <el-form-item label="代驾启用" prop="isDjEnable">
        <el-select v-model="queryParams.isDjEnable" placeholder="代驾启用" clearable size="small">
          <el-option v-for=" dict in djOptions"
                     :key="dict.dictValue"
                     :label="dict.dictLabel"
                     :value="dict.dictValue"/>
        </el-select>
      </el-form-item>
      <el-form-item label="自驾启用" prop="isZjEnable">
        <el-select v-model="queryParams.isZjEnable" placeholder="自驾启用" clearable size="small">
          <el-option v-for=" dict in zjOptions"
                     :key="dict.dictValue"
                     :label="dict.dictLabel"
                     :value="dict.dictValue"/>
        </el-select>
      </el-form-item>
      <el-form-item label="站点类型" prop="stype">
        <el-select v-model="queryParams.stype" placeholder="站点类型" clearable size="small">
          <el-option v-for=" dict in stypeOptions"
                     :key="dict.dictValue"
                     :label="dict.dictLabel"
                     :value="dict.dictValue"/>
        </el-select>
      </el-form-item>

      <el-form-item label="参与活动" prop="inActive">
        <el-select v-model="queryParams.inActive" placeholder="是否参与活动" clearable size="small">
          <el-option v-for=" dict in enableOptions"
                     :key="dict.dictValue"
                     :label="dict.dictLabel"
                     :value="dict.dictValue"/>
        </el-select>
      </el-form-item>

      <el-form-item label="礼品核销" prop="hasVerifyRight">
        <el-select v-model="queryParams.hasVerifyRight" placeholder="是否有礼品核销权限" clearable size="small">
          <el-option v-for=" dict in enableOptions"
                     :key="dict.dictValue"
                     :label="dict.dictLabel"
                     :value="dict.dictValue"/>
        </el-select>
      </el-form-item>


      <el-form-item label="加盟商" prop="agentMobile">
        <el-input
          v-model="queryParams.agentMobile"
          placeholder="请输入加盟商电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['station:station:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['station:station:remove']"
        >删除
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="stationList" @selection-change="handleSelectionChange">
      <el-table-column type="expand">
        <template slot-scope="props">

          <el-card class="box-card">
            <div class="text item">
              <el-row :gutter="24" class="expand-item">
                <el-col :span="6">检测站位置：{{props.row.locAddr}}</el-col>
                <el-col :span="6">检测站坐标：{{props.row.coordinate}}</el-col>
                <el-col :span="6">行政区划：{{props.row.province}}-{{props.row.city}}-{{props.row.region}}</el-col>
                <el-col :span="6">代驾费：{{props.row.stationDriverFee}}/元</el-col>
              </el-row>
              <el-row :gutter="24" class="expand-item">
                <el-col :span="6">营业日期：{{props.row.officeHours}}</el-col>
                <el-col :span="6">上午：{{props.row.am}}</el-col>
                <el-col :span="6">下午：{{props.row.pm}}</el-col>
              </el-row>
              <el-row :gutter="24" class="expand-item">
                <el-col :span="6">普通会员提成：{{props.row.memPermfee1}}</el-col>
                <el-col :span="6">联盟商提成：{{props.row.memPermfee2}}</el-col>
                <el-col :span="6">VIP店长提成：{{props.row.memPermfee3}}</el-col>
              </el-row>
            </div>
          </el-card>
        </template>
      </el-table-column>
      <el-table-column label="检测站图片" align="center" prop="avatar">
        <template slot-scope="scope">
          <el-avatar shape="square" :size="80" :src="ossPreview+ scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="检测站名称" align="center" prop="name"/>
      <el-table-column label="联系电话" align="center" prop="mobile"/>
      <el-table-column label="是否启用" align="center" :formatter="isEnableFormat" prop="isEnable"/>
      <el-table-column label="代驾启用" align="center" :formatter="isDjEnableFormat" prop="isDjEnable"/>
      <el-table-column label="自驾启用" align="center" :formatter="isZjEnableFormat" prop="isZjEnable"/>
      <el-table-column label="站点类型" align="center" :formatter="stypeFormat" prop="stype"/>
      <el-table-column label="加盟商" align="center"  prop="agentMobile"/>
      <el-table-column label="排序" align="center" prop="sort"/>
      <el-table-column label="创建时间" align="center" prop="gmtTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown" >
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['station:station:edit']"
                >修改
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-wallet"
                  @click="handlePrice(scope.row)"
                  v-hasPermi="['station:price:list']"
                >价格体系
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-s-custom"
                  @click="handleDriver(scope.row)"
                  v-hasPermi="['driver:driver:list']"
                >驾驶员
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-s-help"
                  @click="handleUser(scope.row)"
                  v-hasPermi="['station:user:list']"
                >检测站用户
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-s-grid"
                  @click="handleOrder(scope.row)"
                  v-hasPermi="['order:order:list']"
                >订单列表
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改检测站对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" width="55%" v-dialogdrag>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="检测站门头" prop="avatar">
          <station-avatar :station="form" @stationAvatarEvent="emitStationAvatar"
                          ></station-avatar>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="行政区划" prop="name">
              <el-cascader
                ref="cascaderAddr"
                size="medium"
                v-model="areaArr"
                :options="areaoptions"
                @change="handleAddressFun"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站点类型" prop="stype">
              <el-select v-model="form.stype" placeholder="请选择站点类型" clearable size="small">
                <el-option v-for="dict in stypeOptions"
                           :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="parseInt(dict.dictValue)"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="检测站名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入检测站名称"/>
        </el-form-item>
        <el-form-item label="检测站位置" prop="name">
          <el-input v-model="form.locAddr" placeholder="请输入检测站位置"/>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入联系电话"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="isEnable">
              <el-select v-model="form.isEnable" placeholder="请输入是否启用" clearable size="small">
                <el-option v-for="dict in enableOptions"
                           :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="parseInt(dict.dictValue)"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="自驾启用" prop="isEnable">
              <el-select v-model="form.isZjEnable" placeholder="自驾启用" clearable size="small">
                <el-option v-for="dict in enableOptions"
                           :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="parseInt(dict.dictValue)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代驾启用" prop="isEnable">
              <el-select v-model="form.isDjEnable" placeholder="代驾启用" clearable size="small">
                <el-option v-for="dict in enableOptions"
                           :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="parseInt(dict.dictValue)"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="参与活动" prop="inActive">
              <el-select v-model="form.inActive" placeholder="是否参与活动" clearable size="small">
                <el-option v-for="dict in enableOptions"
                           :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="parseInt(dict.dictValue)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="礼品核销" prop="hasVerifyRight">
              <el-select v-model="form.hasVerifyRight" placeholder="是否有礼品核销权限" clearable size="small">
                <el-option v-for="dict in enableOptions"
                           :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="parseInt(dict.dictValue)"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="代驾费" prop="stationDriverFee">
              <el-input-number v-model="form.stationDriverFee" placeholder="请输入代驾费"  :step="1" :min="1"
                               :max="400"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员提成" prop="memPermfee1">
              <el-input-number v-model="form.memPermfee1" placeholder="请输入普通会员提成"  :step="1" :min="0"
                               :max="400"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="联盟商提成" prop="memPermfee2">
              <el-input-number v-model="form.memPermfee2" placeholder="请输入联盟商提成"  :step="1" :min="0"
                               :max="400"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="VIP店长提成" prop="memPermfee3">
              <el-input-number v-model="form.memPermfee3" placeholder="请输入VIP店长提成"  :step="1" :min="0"
                               :max="400"/>
            </el-form-item>
          </el-col>
        </el-row>



        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="stationFee">
              <el-input-number v-model="form.sort" placeholder="请输入排序"  :step="1" :min="1"
                               :max="200"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item label="营业日期" prop="name">
              <el-input v-model="form.officeHours" placeholder="请输入营业日期"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="上午" prop="am">
              <el-input v-model="form.am" placeholder="请输入上午营业时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下午" prop="pm">
              <el-input v-model="form.pm" placeholder="请输入下午营业时间"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="检测站坐标" prop="locPoi">
          <amap :city="this.form.cityCode" :key="this.form.cityCode" @getPosition="getPosition"></amap>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 检测站价格体系 -->
    <el-dialog :title="title" :visible.sync="priceopen" width="1300px" v-dialogdrag append-to-body>
      <station-price :stationId="stationId" :key="(new Date().getTime())"></station-price>
    </el-dialog>

    <!-- 检测站代驾司机列表 -->
    <el-dialog :title="title" :visible.sync="driveropen" width="1300px" v-dialogdrag append-to-body>
      <driver-list :stationId="stationId" :key="(new Date().getTime())"></driver-list>
    </el-dialog>

    <!-- 检测站订单列表 -->
    <el-dialog :title="title" :visible.sync="orderopen" :destroy-on-close="destroy" width="1300px">
      <order-list :stationId="stationId" :key="(new Date().getTime())"></order-list>
    </el-dialog>

    <!-- 检测站用户列表 -->
    <el-dialog :title="title" :visible.sync="useropen" :destroy-on-close="destroy" append-to-body  width="1300px">
      <user-list :stationId="stationId" :key="(new Date().getTime())"></user-list>
    </el-dialog>
  </div>
</template>

<script>
  import {listStation, getStation, delStation, addStation, updateStation, exportStation} from "@/api/station/station";
  import {cascader} from '@/api/cms/region'
  import stationAvatar from "./stationAvatar";
  import StationPrice from "../price/index";
  import defaultSettings from '@/settings';
  import Amap from '@/components/AMap/index'
  import DriverList from './driverList'
  import UserList from './userList'
  import orderList from '../../order/order/index'

  export default {
    name: "Station",
    components: {stationAvatar,StationPrice, Amap,DriverList,orderList,UserList},
    data() {
      return {
        ossPreview: defaultSettings.ossPreview,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 检测站表格数据
        stationList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        priceopen: false,
        driveropen: false,
        orderopen: false,
        useropen: false,
        destroy: true,
        stationId:0,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: undefined,
          mobile: undefined,
          isEnable: undefined,
          isDjEnable: undefined,
          isZjEnable: undefined,
          stype: undefined,
          agentMobile: undefined,
          inActive: undefined,
          hasVerifyRight: undefined
        },
        // 状态数据字典
        enableOptions: [],
        djOptions: [],
        zjOptions: [],
        stypeOptions: [],
        areaoptions: [],
        // 表单参数
        form: {
          name: '',
          avatar: '',
          locPoi: '',
          locAddr: '',
          coordinate: '',
          lng: '',
          lat: '',
          mobile: '',
          isEnable: 1,
          isDjEnable: 1,
          isZjEnable: 1,
          officeHours: '周一至周日',
          am: '08:00-12:00',
          pm: '13:30-17:30',
          stationFee: undefined,
          provinceCode:'',
          cityCode:'',
          regionCode:'',
          province:'',
          city:'',
          region:'',
          sort: 1,
          stationDriverFee: 0,
          memPermfee1: 0,
          memPermfee2: 0,
          memPermfee3: 0,
          stype: 1,
          inActive: 0,
          hasVerifyRight: 0
        },
        areaArr:[],
        // 表单校验
        rules: {
          name: [
            {request: true, message: '请输入检查站名称', trigger: 'blur'},
            {min: 1, max: 20, message: '长度在1到20个字符', trigger: 'blur'}
          ],
          mobile: [
            {validator: mobileValid, trigger: 'blur'}
          ]
        },
        postForm: {
          detailedAddress: '',
          longitude: '',
          latitude: ''
        }
      };
      var mobileValid = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('联系方式不能为空'));
        }
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error('请输入数字值'));
          } else {
            if (value.length > 20) {
              callback(new Error('长度在1到20个字符'));
            } else {
              callback();
            }
          }
        }, 1000);
      }
    },
    created() {
      this.getList();
      this.getDicts("sys_is_enable").then(response => {
        this.enableOptions = response.data;
        this.djOptions = response.data;
        this.zjOptions = response.data;
      });
      this.getDicts("station_stype").then(response => {
        this.stypeOptions = response.data;
      });
      this.areaCascader();
    },
    methods: {
      /** 查询检测站列表 */
      getList() {
        this.loading = true;
        listStation(this.queryParams).then(response => {
          this.stationList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      areaCascader() {
        cascader().then(res => {
          this.areaoptions = res.data;
        })
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          name: undefined,
          avatar: undefined,
          locPoi: "郑州市人民政府",
          locAddr: "",
          coordinate: "113.625351,34.746303",
          mobile: undefined,
          isEnable: 1,
          isDjEnable: 1,
          isZjEnable: 1,
          officeHours: '周一至周日',
          am: '08:00-12:00',
          pm: '13:30-17:30',
          gmtTime: undefined,
          provinceCode:'',
          cityCode:'',
          regionCode:'',
          province:'',
          city:'',
          region:'',
          sort: 1,
          stationDriverFee: 0,
          memPermfee1: 0,
          memPermfee2: 0,
          memPermfee3: 0,
          stype: 1
        };
        this.resetForm("form");
        this.areaArr = [];
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加检测站";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getStation(id).then(response => {
          this.form = response.data;
          this.areaArr[0] = this.form.provinceCode;
          this.areaArr[1] = this.form.cityCode;
          this.areaArr[2] = this.form.regionCode;
          this.open = true;
          this.title = "修改检测站";
          var coors = this.form.coordinate.split(",");
          this.postForm.longitude = coors[0];
          this.postForm.latitude = coors[1];
          this.postForm.detailedAddress = this.form.locPoi;
        });
      },
      handlePrice(row) {
        this.priceopen = true;
        this.stationId = row.id;
        this.title = "检测站价格体系";
      },
      handleDriver(row) {
        this.driveropen = true;
        this.stationId = row.id;
        this.title = "驾驶员列表";
      },

      handleUser(row) {
        this.useropen = true;
        this.stationId = row.id;
        this.title = "检测站用户列表";
      },

      handleOrder(row) {
        this.orderopen = true;
        this.stationId = row.id;
        this.title = "检测站订单";
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.coordinate = location.lng + "," + location.lat;
            this.form.coordinate = this.postForm.longitude + "," + this.postForm.latitude;
            this.form.locPoi = this.postForm.detailedAddress;


            if (this.form.id != undefined) {
              updateStation(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              addStation(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除检测站编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delStation(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有检测站数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportStation(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function () {
        });
      },
      emitStationAvatar(data) {
        this.form.avatar = data;
      },
      getPosition({address, lat, lng, name}) {
        this.postForm.detailedAddress = address;
        this.postForm.longitude = String(lng);
        this.postForm.latitude = String(lat);
      },
      handleAddressFun: function(value){
        console.log(value)
        var node = this.$refs['cascaderAddr'].getCheckedNodes()[0];
        var  thsAreaCode = node.pathLabels   //注意2： 获取label值
        console.log(thsAreaCode)
        this.form.provinceCode = value[0];
        this.form.cityCode = value[1];
        this.form.regionCode = value[2];
        this.form.province = thsAreaCode[0];
        this.form.city = thsAreaCode[1];
        this.form.region = thsAreaCode[2];
      },
      isEnableFormat(row, column) {
        return this.selectDictLabel(this.enableOptions, row.isEnable);
      },
      isDjEnableFormat(row, column) {
        return this.selectDictLabel(this.djOptions, row.isDjEnable);
      },
      isZjEnableFormat(row, column) {
        return this.selectDictLabel(this.zjOptions, row.isZjEnable);
      },
      stypeFormat(row, column) {
        return this.selectDictLabel(this.stypeOptions, row.stype);
      }
    }

  };
</script>
<style>
  .expand-item {
    margin-top: 15px;
  }
</style>
